<?php

class Category_model extends CI_Model {

    function __construct() {
        parent::__construct();
    }
    
    function getCategory_all() {
        $query = $this->db->order_by("name", "asc")->get('category');

        $arr = array();
        foreach ($query->result() as $row) {
            $arr[] = $row;
        }
        return $arr;
    }
    
    function countNovel_by_category($catId) {
        $sql = 'SELECT count(*) as count FROM relationship WHERE cid=' .$catId;
        $query = $this->db->query($sql)->row();
        return $query->count;
    }
    
    function addCategory($arr) {
        $data = array(
            'name' => $arr['name'],
            'slug' => slug($arr['name'])
        );
        $result = $this->db->insert('category', $data);
        return $result;
    }
    
    /**
     * Validate manga infor before add to DB 
     * @param type $arr array data of manga 
     * @return type 
     */
    function addCategory_validate($arr) {
        extract($arr);

        $err = 0;
        $msg = array();
        // validate category name
        if (!$this->validateName($name)) {
            $err = -1;
            $msg['name'] = 'Category Name invalid';
        } else if ($this->checkNameExist($name)) {
            $msg['name'] = 'Category name exist';
            $err = -3;
        }
        return array('err' => $err, 'msg' => $msg);
    }
    
    function editCategory($arr) {
        $data = array(
            'name' => $arr['name'],
            'slug' => slug($arr['name'])
        );

        $this->db->where('id', $arr['id']);
        $result = $this->db->update('category', $data);
        return $result;
    }
    
    /**
     * Remove a category out of Database
     * @param type $id id of category
     * @return type 
     */
    function removeCategory($id) {
        return $this->db->delete('category', array('id' => $id));
    }

    private function validateName($name) {
        return strlen($name) <= 100;
    }

    private function checkNameExist($name) {
        $query_u = $this->db->get_where('category', array('name' => $name));
        return $query_u->num_rows > 0;
    }
    
}